<?php

class DefaultController extends Controller {

    /**
     * @var string the default layout for the views.
     */
    public $layout = '//layouts/column2';
    public $admin = true;

    /**
     * @var private property containing the associated model instance.
     */
    private $_entity = null;

    /**
     * Define filters for this Controllers
     * @return array Array of filters
     */
    public function filters() {
//        return array(
//            array('CrugeAccessControlFilter'),
//            'entityContext + submit', //check to ensure valid entity context
//        );
    }

    /**
     * Main action to manage Nosey Forms
     */
    public function actionIndex() {
        $model = new Form('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['Form']))
            $model->attributes = $_GET['Form'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * Action to submit a form
     * @param type $id
     */
    public function actionSubmit($id, $entity_id = null) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);
        $result = array();

//        $this->performAjaxValidation($form_model);
        if (Yii::app()->request->isAjaxRequest) {
            if (isset($_POST['DynamicFormModel'])) {
                $form_model->attributes = $_POST['DynamicFormModel'];
//            $this->performAjaxValidation($form_model);
                if ($form_model->validate()) {
                    $transaction = Yii::app()->db->beginTransaction();
                    try {
                        $answer = new Answer;
                        $answer->entity_id = $entity_id;
                        $answer->creation_date = date('Y-m-d H:i:s');

                        if (!$answer->save())
                            throw new Exception("Error Saving Answer");

                        foreach ($_POST['DynamicFormModel'] as $field => $content) {
                            $field_value = new FieldValue;
                            if (is_array($content)) {
                                $field_value->content = json_encode($content);
                            } else {
                                $field_value->content = $content;
                            }
//                        $field_value->content = $content;
                            $field_value->answer_id = $answer->id;
                            $field_value->field_id = $field;

                            if (!$field_value->save())
                                throw new Exception("Error Saving Field Value");
                        }

                        $transaction->commit();
                        Yii::app()->user->setFlash('success', Yii::t('noseyModule.app', 'Answers saved successfully!'));

                        $url = $postPerPage = Yii::app()->controller->module->after_submit_url;
                        if (!$url || $url == null)
                            $this->redirect(array('thanks'));
                        else
                            $this->redirect($url);
                    } catch (Exception $ex) {
                        $transaction->rollBack();
                        Yii::app()->user->setFlash('error', Yii::t('noseyModule.app', 'There was an error saving the answers.'));
                    }
                } else {
                    $result['success'] = false;
                    $result['errors'] = $form_model->errors;
//                     echo json_encode($result);
                }
            }
            echo json_encode($result);
        } else {


            $this->render('submit', array(
                'model' => $model,
                'form_model' => $form_model,
            ));
        }
    }

    public function actionSubmit2($id) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);

//        $this->performAjaxValidation($form_model);

        if (isset($_POST['DynamicFormModel'])) {
            $form_model->validate();
            var_dump($form_model->errors);
            die();
            $form_model->attributes = $_POST['DynamicFormModel'];

            $this->performAjaxValidation($form_model);
            if ($form_model->validate()) {
                $transaction = Yii::app()->db->beginTransaction();

                try {
                    $answer = new Answer;
                    $answer->entity_id = $this->_entity->id;
                    $answer->creation_date = date('Y-m-d H:i:s');

                    if (!$answer->save())
                        throw new Exception("Error Saving Answer");

                    foreach ($_POST['DynamicFormModel'] as $field => $content) {
                        $field_value = new FieldValue;
                        $field_value->content = $content;
                        $field_value->answer_id = $answer->id;
                        $field_value->field_id = $field;

                        if (!$field_value->save())
                            throw new Exception("Error Saving Field Value");
                    }

                    $transaction->commit();
                    Yii::app()->user->setFlash('success', Yii::t('noseyModule.app', 'Answers saved successfully!'));

                    $url = $postPerPage = Yii::app()->controller->module->after_submit_url;
                    if (!$url || $url == null)
                        $this->redirect(array('thanks'));
                    else
                        $this->redirect($url);
                } catch (Exception $ex) {
                    $transaction->rollBack();
                    Yii::app()->user->setFlash('error', Yii::t('noseyModule.app', 'There was an error saving the answers.'));
                }
            }
        }

        $this->render('submit_2', array(
            'model' => $model,
            'form_model' => $form_model,
        ));
    }

    public function actionFormulario($id, $entity_id) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);
        $this->performAjaxValidation($form_model);
        if (isset($_POST['DynamicFormModel'])) {

            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate()) {

                $result = $this->SaveNoseyForm($_POST['DynamicFormModel'], $entity_id);
                if ($result['success'] == true) {
//                    TODO cambiar el local host
                    $url = "localhost" . $this->createUrl('/nosey/default/index');
//                   $this->redirect(Yii::app()->homeUrl.'site/login');
                }
            } else {

                $result['success'] = false;
                $result['data'] = $form_model->errors;
            }
            echo json_encode($result);
        } else {

            $this->render('formulario', array(
                'model' => $model,
                'form_model' => $form_model,
            ));
        }
    }

    // formulario simple en modal
    public function actionModalFormulario($id, $entity_id) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);
        $this->performAjaxValidation($form_model);
        if (isset($_POST['DynamicFormModel'])) {

            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate()) {

                $result = $this->SaveNoseyForm($_POST['DynamicFormModel'], $entity_id);
            } else {

                $result['success'] = false;
                $result['data'] = $form_model->errors;
            }
            echo json_encode($result);
        } else {

            $this->renderPartial('_formulario', array(
                'model' => $model,
                'entity_id' => $entity_id,
                'form_model' => $form_model,
                    ), false, true);
        }
    }

    public function actionThanks() {
        $this->render('thanks');
    }

    public function actionMissingTranslation($category, $message, $language) {
        Yii::t($category, $message, null, null, $language);
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id, $modelClass = __CLASS__) {
        $model = Form::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model, $form = null) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'form-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Protected method to load the associated Project model class
     * @param integer projectId the primary identifier of the associated Project
     * @return object the Project data model based on the primary key
     */
    protected function loadEntity($entityId) {
        $entity_model = $postPerPage = Yii::app()->controller->module->entity_model;

        if (!$entity_model)
            throw new CHttpException(400, 'You have to specify the model to associate in the config file.');
        if ((@include $entity_model . '.php') === false)
            throw new CHttpException(404, 'The associated model can not be loaded.');

        //if the project property is null, create it based on input id
        if ($this->_entity === null) {
            $this->_entity = $entity_model::model()->findByPk($entityId);

            if ($this->_entity === null)
                throw new CHttpException(404, 'The requested entity does not exist.');
        }
        return $this->_entity;
    }

    /**
     * In-class defined filter method, configured for use in the above filters()
     * method. It is called before the actionCreate() action method is run in
     * order to ensure a proper project context
     */
    public function filterEntityContext($filterChain) {
        //set the project identifier based on GET input request variables
        if (isset($_GET['eid']))
            $this->loadEntity($_GET['eid']);
        else
            throw new CHttpException(403, 'Must specify an entity before performing this action.');
        //complete the running of other filters and execute the requested action
        $filterChain->run();
    }

    public function actionSubmitModal($id = null, $validador = false) {
        $id_usuario = 1;
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);

        $this->performAjaxValidation($form_model);

        if (isset($_POST['DynamicFormModel'])) {

            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate() && $validador) {

                $result = $this->SaveNoseyForm($_POST['DynamicFormModel'], $id_usuario);
            } else {

                $result['success'] = false;
                $result['data'] = $form_model->errors;
            }
            echo json_encode($result);
        } else {


            $this->renderPartial('_submit_modal', array(
                'model' => $model,
                'form_model' => $form_model,
                    ), false, true);
        }
    }

    public function actionFormularioModal($id, $entity_id, $validador = false) {
        $model = $this->loadModel($id);
        $form_model = new DynamicFormModel($model);

        $this->performAjaxValidation($form_model);

        if (isset($_POST['DynamicFormModel'])) {

            $form_model->attributes = $_POST['DynamicFormModel'];
            if ($form_model->validate() && $validador) {
                $result = $this->SaveNoseyForm($_POST['DynamicFormModel'], $entity_id);
            } else {

                $result['success'] = false;
                $result['data'] = $form_model->errors;
            }
            echo json_encode($result);
        } else {

            $this->renderPartial('_formulario_modal', array(
                'model' => $model,
                'entity_id' => $entity_id,
                'form_model' => $form_model,
                    ), false, true);
        }
    }

    public function SaveNoseyForm($model_form, $id_entrada) {

        $result = array();
        $transaction = Yii::app()->db->beginTransaction();
        try {
            $answer = new Answer;
            $answer->entity_id = $id_entrada;
            $answer->creation_date = Util::FechaActual();

            if (!$answer->save())
                throw new Exception("Error Saving Answer");

            foreach ($model_form as $field => $content) {
                $field_value = new FieldValue;
                if (is_array($content)) {
                    $field_value->content = json_encode($content);
                } else {
                    $field_value->content = $content;
                }
                $field_value->answer_id = $answer->id;
                $field_value->field_id = $field;
                if (!$field_value->save())
                    throw new Exception("Error Saving Field Value");
            }
            $transaction->commit();
            $result['success'] = TRUE;
            $result['message'] = 'Información almacenada con exito';
            return $result;
        } catch (Exception $ex) {
            $transaction->rollBack();
            $result['success'] = false;
            $result['message'] = 'No se pudo guardar la informacion';
            return $result;
        }
    }

    /**
     * action que muestra las respuestas que un usuario ha contestado 
     * @param int $id del formulario que se respondio
     */
    public function actionRespuestasFormulario($id) {

        if (Yii::app()->request->isAjaxRequest) {
            $model = NoseyEntidadAnswer::model()->findByPk($id);
            $respuesta = $model->answers;
            $encuesta = $model->form;
            $this->renderPartial('_respuestas_formulario', array('respuesta' => $respuesta,
                'encuesta' => $encuesta,
                    ), false, true);
        }
    }

    public function actionReportFrmHistoria($id) {
        $model = new NoseyEntidadAnswer('search');
        $model->unsetAttributes(); // clear any default values
        $model->nosey_form_id = $id;

        if (isset($_GET['search'])) {
            if (!empty($_GET['search']['value'])) {
                $n = explode(' - ', $_GET['search']['value']);
                $model->date_first = $n['0'];
                $model->date_last = $n['1'];
            }
        }
        $this->render('reportFrmHistorial', array(
            'model' => $model,
        ));
    }

    public function actionHistorialEntidad($entidad_tipo, $entidad_id) {
        $campania = Campania::model()->findByPk($entidad_id);

        $model = new NoseyEntidadAnswer('search');
        $model->unsetAttributes(); // clear any default values
        $model->entidad_tipo = $entidad_tipo;
        $model->entidad_id = $entidad_id;
        $model->nosey_form_id = $campania->nosey_form_id;

        if (isset($_GET['search'])) {
            if (!empty($_GET['search']['value'])) {
                $n = explode(' - ', $_GET['search']['value']);
                $model->date_first = $n['0'];
                $model->date_last = $n['1'];
            }
        }
        $this->render('historial_por_entidad', array(
            'model' => $model,
            'formulario' => $campania->nosey_form_id,
        ));
    }

    /**
     * @author Sofía Mejía
     * @param strign $fecha recupera el intervalo de las fechas seleccionadas
     * @param $tring $encuesta_id un string con todos los formularios seleccionados 
     */
    public function actionExportar($fecha, $idformulario, $entidad_id = null, $entidad_tipo = null) {

        $fechaIni = substr($fecha, 0, 10);
        $fechaFin = substr($fecha, 13, 20);
        $datos = array();
        $encuestas = array();
        $model = new NoseyEntidadAnswer('search');
        $model->unsetAttributes(); // clear any default values
        //para generar excel desde historial_por_entidad
        if (!empty($entidad_id) && !empty($entidad_tipo)) {
            if ($_POST['Encuesta'] == 'todos') {
                ($fecha != null || $fecha != '') ? $encuestas = $model->rango($fechaIni, $fechaFin)->de_entidad_tipo($entidad_tipo)->de_entidad_id($entidad_id)->de_formulario_id($idformulario)->findAll() :
                                $encuestas = $model->de_entidad_tipo($entidad_tipo)->de_entidad_id($entidad_id)->de_formulario_id($idformulario)->findAll();
            } else {
//            Coloca en $data solo los id de los formularios  seleccionadas
                $registros = explode(',', $_POST['Encuesta']);
                foreach ($registros as $registro_id) {
                    $datos = $model->findByPk($registro_id);
                    array_push($encuestas, $datos);
                }
            }
        }
        //para generar excel desde reportFrmHistorial
        else {
            if ($_POST['Encuesta'] == 'todos') {
                ($fecha != null || $fecha != '') ? $encuestas = $model->rango($fechaIni, $fechaFin)->de_formulario_id($idformulario)->findAll() :
                                $encuestas = $model->de_formulario_id($idformulario)->findAll();
            } else {
//            Coloca en $data solo los id de los formularios  seleccionadas
                $registros = explode(',', $_POST['Encuesta']);
                foreach ($registros as $registro_id) {
                    $datos = $model->findByPk($registro_id);
                    array_push($encuestas, $datos);
                }
            }
        }
        $grid = $model->createGrid($idformulario);
        $preguntas = $model->obtenerPreguntas($idformulario);

        if (!empty($encuestas)) {
            $objExcel = new PHPExcel();
            $objExcel->setActiveSheetIndex(0) // Titulo del reporte
                    ->setCellValue('A1', 'Cuenta')  //Titulo de las columnas
                    ->setCellValue('B1', 'Contacto')
                    ->setCellValue('C1', 'Identificacion')
                    ->setCellValue('D1', 'Campaña')
                    ->setCellValue('E1', 'Formulario')
                    ->setCellValue('F1', 'Fecha')
            ;
            //Devuelve la ultima columna utilizada en este caso la F
            $lastColumn = $objExcel->getActiveSheet()->getHighestColumn();
            $lastTitles = $lastColumn;
            foreach ($grid as $col) {
                //va iterando desde la E,F,G...n en la fila 1 ($head)
                $lastTitles++;
                $objExcel->setActiveSheetIndex(0)->setCellValue($lastTitles . '1', $col['header']);
            }

            $id = 2;
            foreach ($encuestas as $data) {
                $lastContent = $lastColumn;
                $objExcel->setActiveSheetIndex(0)
                        ->setCellValue('A' . $id, $data->contactorel->cuenta->nombre ? $data->contactorel->cuenta->nombre : "")
                        ->setCellValue('B' . $id, $data->contactorel->nombre_completo)  //Titulo de las columnas
                        ->setCellValue('C' . $id, $data->contactorel->documento)
                        ->setCellValue('D' . $id, $data->entidad_id)
                        ->setCellValue('E' . $id, $data->form->name)
                        ->setCellValue('F' . $id, Util::FormatDate($data->answers->creation_date, "d/m/Y H:m:s"))
                ;
                foreach ($preguntas as $pregunta) {
                    //va iterando desde la E,F,G...n en la fila 1 ($head)
                    $temp = NoseyEntidadAnswer::model()->obtenerRespuesta($data->answers->id, $pregunta['field_id']);
                    $lastContent++;
                    $objExcel->setActiveSheetIndex(0)->setCellValue($lastContent . $id, $temp);
                }
                $id++;
            }
            $objExcel->getActiveSheet()->setTitle('Reporte Formularios');
//       Se activa la hoja para que sea la que se muestre cuando el archivo se abre
            $objExcel->setActiveSheetIndex(0);
            for ($i = 'A'; $i <= $lastContent; $i++) {
                $objExcel->setActiveSheetIndex(0)->getColumnDimension($i)->setAutoSize(TRUE);
            }
////// Inmovilizar paneles
            $objExcel->getActiveSheet(0)->freezePaneByColumnAndRow(1, 2);
//        // Se manda el archivo al navegador web, con el nombre que se indica, en formato 2007
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="Reporte Formularios.xlsx"');
            header('Cache-Control: max-age=0');

            $objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }

    /*     * *******************funciones ajax**************************************************** */

    /**
     * @author Alex Yepez <ayepez@tradesystem.com.ec>
     * Creaccion del registro de las la entidad que respondera la encuesta
     * @param type $entidad_tipo
     * @param type $entidad_id
     * @param type $contacto
     * @param type $form_id
     * @param type $subentidad_tipo
     * @param type $subentidad_id
     */
    public function actionAjaxCreateEntidadAnswer($entidad_tipo, $entidad_id, $contacto, $form_id, $modalView, $subentidad_tipo = null, $subentidad_id = null) {
        $model = new NoseyEntidadAnswer();
        $model->entidad_tipo = $entidad_tipo;
        $model->entidad_id = $entidad_id;
        $model->contacto = $contacto;
        $model->nosey_form_id = $form_id;
        if ($subentidad_tipo) {
            $model->subentidad_tipo = $subentidad_tipo;
        }
        if ($subentidad_id) {
            $model->subentidad_id = $subentidad_id;
        }
        if ($model->save()) {
            if ($modalView == 'slider') {
                $this->actionFormularioModal($model->nosey_form_id, $model->id);
            } elseif ($modalView == 'standar') {
                $this->actionModalFormulario($model->nosey_form_id, $model->id);
            }
        }
    }

}
